package models

import (
	"3rd/errors"
	"3rd/utils"
	"github.com/garyburd/redigo/redis"
	"uc/app/db"
)

type captcha struct {
	len    int
	expire int
}

func NewCaptcha(len, expire int) *captcha {
	return &captcha{len, expire}
}

func (this *captcha) GenCaptcha(media string) (string, error) {
	captcha := utils.RandStringRunes(this.len)

	c := db.RedisPool.Get()
	defer c.Close()
	r, err := redis.String(c.Do("SET", media, captcha, "nx", "ex", this.expire))
	if err != nil || r != "OK" {
		return "", errors.New(RetryLater, err)
	}
	return captcha, nil
}

func (this *captcha) Validate(media, captcha string) error {
	c := db.RedisPool.Get()
	defer c.Close()
	// weather the captcha exists
	val, err := redis.String(c.Do("GET", media))
	if err != nil || val != captcha {
		return errors.New(InvalidCaptcha, "captcha invalid")
	}

	return nil
}
